require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import "android.content.Intent"
import "android.net.Uri"
import "android.provider.DocumentsContract"
import "java.net.URLDecoder"
import "java.io.File"
import "java.io.FileInputStream"
import "java.io.FileOutputStream"
import "init"
import "helper"

pcall(function()
  androidhwext={R=luajava.bindClass("androidhwext.R")}
  activity.setTheme(androidhwext.R.style.Theme_Emui)
end)
local array = activity.obtainStyledAttributes({
  android.R.attr.colorAccent,
  android.R.attr.textColorPrimary,
})
colorAccent=array.getColorStateList(0)
textColorPrimary=array.getColorStateList(1)
activity.setContentView(loadlayout("layout"))
activity.getActionBar().setSubtitle("v"..appver)
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
TEMP_DIR_PATH=activity.getExternalCacheDir().getPath().."/temp"
ALP_PICK_CODE=1
ZIP_SAVE_CODE=2

alpPathSelectButton.onClick=function()
  local intent = Intent(Intent.ACTION_GET_CONTENT)
  intent.setType("application/octet-stream")
  intent.addCategory(Intent.CATEGORY_OPENABLE)
  activity.startActivityForResult(intent,ALP_PICK_CODE)
end

zipPathSelectButton.onClick=function()
  local intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
  intent.addCategory(Intent.CATEGORY_OPENABLE)
  intent.setType("application/zip")
  intent.putExtra(Intent.EXTRA_TITLE, "MyApplication.zip");
  activity.startActivityForResult(intent,ZIP_SAVE_CODE)
end

switchButton.onClick=function()
  --校验输入
  --输入路径, 输出路径, 工作路径
  local inputPath=alpPathEdit.text
  local outputPath=zipPathEdit.text
  local err
  if inputPath=="" then
    alpPathEdit.setError("请输入文件路径")
    err=true
  end
  if outputPath=="" then
    zipPathEdit.setError("请输入文件路径")
    err=true
  end
  if err then
    return
  end

  --复制文件
  local workDirPath=TEMP_DIR_PATH.."/"..System.currentTimeMillis()
  File(workDirPath).mkdirs()
  local workDir=File(workDirPath)
  if inputPath:find("://") then
    if not xpcall(function()
        local uri=Uri.parse(inputPath)
        local inputStream=activity.getContentResolver().openInputStream(uri)
        --真正的输入文件路径
        inputPath=workDirPath..".zip"

        --复制文件
        local outStream=FileOutputStream(inputPath)
        LuaUtil.copyFile(inputStream, outStream)
        outStream.close()
      end,
      function(err)
        alpPathEdit.setError(err:match("Exception: (.*)\n"))
      end) then
      return--有错误就中断执行代码
    end
  end
  local formatList=require("template.formatList")

  local inputFile=File(inputPath)
  if inputFile.isFile() then
    --alp解压路径
    local workAlpPath=workDirPath.."/alpUnzip"
    if pcall(LuaUtil.unZip,inputPath,workAlpPath) then
      --读取init.lua
      local config={}
      local loadFunc,err=loadfile(workAlpPath.."/init.lua","bt",config)
      if loadFunc then
        if not xpcall(loadFunc,function(err)
            AlertDialog.Builder(this)
            .setTitle("init.lua 运行时错误")
            .setMessage(err)
            .setPositiveButton(android.R.string.ok,nil)
            .show()
            LuaUtil.rmDir(workDir)
          end) then
          return
        end
       else
        AlertDialog.Builder(this)
        .setTitle("init.lua 语法错误")
        .setMessage(err)
        .setPositiveButton(android.R.string.ok,nil)
        .show()
        LuaUtil.rmDir(workDir)
        return
      end
      local permissions=""
      if config.user_permission then
        permissions=table.concat(config.user_permission,[["/>

    <uses-permission android:name="android.permission.]])
        if permissions~="" then
          permissions=[[

    <uses-permission android:name="android.permission.]]..permissions..[["/>
]]
        end
      end
      --工作目录
      local workProjectPath=workDirPath.."/project"
      LuaUtil.unZip(activity.getLuaDir("template").."/template.zip",workProjectPath)
      for index,content in ipairs(formatList) do
        local path=workProjectPath.."/"..content
        local file=io.open(path)
        local content=file
        :read("*a")
        :gsub("{{appName}}",config.appname or "Aide Lua")
        :gsub("{{appPackageName}}",config.packagename or "")
        :gsub("{{permissions}}",permissions)
        :gsub("{{versionName}}",config.appver or "1.0")
        :gsub("{{versionCode}}",config.appcode or "1.0")
        file:close()
        io.open(path,"w")
        :write(content)
        :close()
      end
      LuaUtil.copyDir(workAlpPath,workProjectPath.."/app/src/main/assets_bin")

      if workAlpPath.."/icon.png" then
        LuaUtil.copyFile(workAlpPath.."/icon.png",workProjectPath.."/app/src/main/res/drawable/ic_launcher.png")
      end

      LuaUtil.zip(workProjectPath,workDirPath)

      if outputPath:find("://") then
        local uri=Uri.parse(outputPath)
        local pfd = activity.getContentResolver().openFileDescriptor(uri, "w")
        local fileOutputStream = FileOutputStream(pfd.getFileDescriptor())
        local fileInputStream=FileInputStream(workDirPath.."/project.zip")
        LuaUtil.copyFile(fileInputStream,fileOutputStream)
       else
        LuaUtil.copyFile(workDirPath.."/project.zip",outputPath)
      end
      showToast("转换完成")
     else--ALP解压失败
      showToast("ALP解压失败")
    end
    inputFile.delete()
    LuaUtil.rmDir(workDir)
   else--未找到ALP
    alpPathEdit.setError("未找到文件")
  end
end

function onActivityResult(requestCode,resultCode,data)
  if resultCode == Activity.RESULT_OK then
    if requestCode==ALP_PICK_CODE then
      local uri = data.getData()
      alpPathEdit.setText(tostring(uri))
      alpPathEdit.setError(nil)
     elseif requestCode==ZIP_SAVE_CODE then
      local uri = data.getData()
      --DocumentsContract.deleteDocument(activity.getContentResolver(), uri)
      zipPathEdit.setText(tostring(uri))
      zipPathEdit.setError(nil)
    end
  end
end


function onError(title,message)
  AlertDialog.Builder(this)
  .setTitle(tostring(title))
  .setMessage(tostring(message))
  .setPositiveButton(android.R.string.ok,nil)
  .show()
  return true
end